package pe.gob.inei.fx.lib.component.renderer
{
	import flash.events.Event;
	
	import mx.controls.Alert;
	import mx.controls.CheckBox;
	import mx.core.IFactory;
	
	import pe.gob.inei.fx.lib.component.events.DispatcherEvent;
	import pe.gob.inei.fx.lib.component.events.ListCheckItemRendererEvent;
	
	public class ListCheckItemRenderer extends CheckBox implements IFactory {
		
		private var _propiedadSeleccion:String;
		private var _labelField:String;
		private var _campo:String;
		
		private var dispatcher:DispatcherEvent = DispatcherEvent.instance(ListCheckItemRendererEvent);
		
		public function ListCheckItemRenderer(propiedadSeleccion:String, labelField:String, campo:String) {
			selectedField = propiedadSeleccion;
			_propiedadSeleccion = propiedadSeleccion;
			_labelField = labelField;
			_campo = campo;
			
			addEventListener(Event.CHANGE, onChangeHandler);
		}
		
		private function onChangeHandler(event:Event):void {
			data[_propiedadSeleccion] = !data[_propiedadSeleccion];
			dispatcher.dispatchEvent(new ListCheckItemRendererEvent(ListCheckItemRendererEvent.CHECK_ITEM_SELECTED, data, this));
		}
		
		private function maxSelectedQuitHandler(event:ListCheckItemRendererEvent):void {
			event.data[_propiedadSeleccion] = true;
			event.objeto.selected = true;
			Alert.show("El esquema de datos debe mostrar al menos un indicador", "Información");
		}
		
		override public function set data(value:Object):void {
			super.data = value;
			if(!dispatcher.hasEventListener(ListCheckItemRendererEvent.MAX_SELECTED_QUIT + value[_campo]))
				dispatcher.addEventListener(ListCheckItemRendererEvent.MAX_SELECTED_QUIT + value[_campo], maxSelectedQuitHandler);
			label = value[_labelField];
		}
		
		public function newInstance():* {
			return new ListCheckItemRenderer(_propiedadSeleccion, _labelField, _campo);
		}
	}
}
